package gz.itcast.d_callable;

import gz.itcast.util.JdbcUtil;
import org.junit.Test;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;

/**
 * Created 吴海杰 on 2017/2/27.
 */
public class Demo1 {
    @Test
    public void test1() {
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs=null;
        try {
            conn = JdbcUtil.getConnection();
            String sql = "CALL pro_findById(?);";
            //预编译
            stmt=conn.prepareCall(sql);
            stmt.setInt(1,2);
            rs = stmt.executeQuery();
           //遍历结果
            while (rs.next()){
                int id=rs.getInt("id");
                String name=rs.getString("name");
                String gender =rs.getString("gender");
                System.out.println(id+","+name+","+gender);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }
//执行带有输出参数的存储过程
    @Test
    public void test2() {
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet rs=null;
        try {
            conn = JdbcUtil.getConnection();
            String sql = "CALL pro_findById2(?,?);";
            //预编译
            stmt=conn.prepareCall(sql);
            stmt.setInt(1,3);
            stmt.registerOutParameter(2, Types.VARCHAR);
            stmt.executeQuery();//没有结果集返回，而是返回到输出参数中
            String result= stmt.getString(2);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }
}
